package easy;

import org.junit.Test;

public class a67_二进制求和 {
    public String addBinary(String a, String b) {
        char[] charsA = a.toCharArray();
        char[] charsB = b.toCharArray();
        char[] res = new char[Math.max(charsA.length, charsB.length) + 1];
        if (charsA.length > charsB.length) {
            System.arraycopy(charsA, 0, res, 1, charsA.length);
        } else {
            System.arraycopy(charsB, 0, res, 1, charsB.length);
        }
        boolean carry = false;
        int ai = charsA.length - 1;
        int bi = charsB.length - 1;
        int i = res.length - 1;
        while (ai >= 0 && bi >= 0) {
            int sum = charsA[ai--] + charsB[bi--] - 96;
            if (carry) sum++;
            if (sum == 0) {
                res[i--] = '0';
                carry = false;
            } else if (sum == 1) {
                res[i--] = '1';
                carry = false;
            } else if (sum == 2) {
                carry = true;
                res[i--] = '0';
            } else {
                carry = true;
                res[i--] = '1';
            }
        }
        while (i >= 0) {
            switch (res[i]) {
                case 0:
                    if (carry) res[i] = '1';
                    break;
                case '0':
                    if (carry) {
                        carry = false;
                        res[i] = '1';
                    }
                    break;
                case '1':
                    if (carry) {
                        carry = true;
                        res[i] = '0';
                    }
                    break;
            }
            i--;
        }
        if (res[0] == 0) {
            if (charsA.length < charsB.length) charsA = charsB;
            System.arraycopy(res, 1, charsA, 0, charsA.length);
            return new String(charsA);
        }
        return new String(res);
    }

    @Test
    public void test() {
        System.out.println(addBinary("0", "0"));
    }
}
